<template>
	<view class="login">
		<uni-nav-bar :title="$t('General.home.login')" class="u-f-ajc loginNav" :statusBar="true" :fixed="true">
			<view slot="left">
				<uni-icons v-if="isPhone" @click="backAction()" type="back" size="25"></uni-icons>
			</view>
		</uni-nav-bar>
		<view class="logo">
			<image src="../../../static/images/logo.png" mode="widthFix" class="logo-icon"></image>
			
		</view>
		<view class="form" style="padding: 0 55rpx;">
			<form @submit.stop.prevent="formSubmit">
				<view class="" v-if="isPhone">
					<label class="form-item">
						<text class="form-item-title">{{$t('General.login.account')}}</text>
						<input type="text" :placeholder="$t('General.login.enterAccount')" name="uname" :value="uname" @input="bindinputUname"/>
					</label>
					<label class="form-item space-between">
						<view class="left">
							<text class="form-item-title">{{$t('General.login.password')}}</text>
							<input  type="text" password :placeholder="$t('General.login.enterPassword')" :password="showPassword" name="upass" :value="upass" @input="bindinputUpass"/>
						</view>
						<view style="z-index:999" @click.stop="changePassword">
							<uni-icons style="" color="#666" custom-prefix="custom-icon" :type="showPassword ? 'eye-slash' : 'eye'" size="22"></uni-icons>
						</view>
					</label>
					<view class="" style="display: flex;justify-content: space-between;" >
						<view style="margin-top: 20rpx;" class="forgetPwd u-f-ac" >
							<checkbox-group style="display: flex;align-items: center;" @change="rememberPswd">
								<checkbox style="transform:scale(0.7)" :checked="isRemember"/><view>{{$t('General.login.rememberPassword')}}</view>
							</checkbox-group>
						</view>
						<view style="margin-top: 20rpx;" class="forgetPwd u-f-ac" @tap="forgetAction" data-code="600009" data-eventName="click_login_forget_password">
							{{$t('General.login.account_reset_forget_password')}}
							<uni-icons type="help" color="#666" size="20">
							</uni-icons>
						</view>
					</view>
				</view>

				<view v-if="!isPhone" class="form-item form-item-submit">
					<!-- #ifdef MP-WEIXIN -->
					<button class="block radius-btn" :open-type="isRead?'getUserInfo':''" @getphonenumber="getPhoneNumber"
						@chooseavatar="onChooseAvatar" @getuserinfo="bindgetuserinfo" type="primary"
						style="margin-bottom: 40rpx" @tap="onWeixinLogin">一键登录</button>
					<!-- #endif -->
					<button class="block radius-btn" @click="iphoneLogin" type="primary" plain
						style="margin-bottom: 10rpx">{{$t('General.login.accountPasswordLogin')}}</button>
				</view>
				<view v-if="isPhone" class="form-item form-item-submit">
					<button class="block radius-btn" @click="iphoneLogin" type="primary" form-type="submit"
						style="margin-bottom: 10rpx" data-code="600014" data-eventName="click_login_btn">{{$t('General.login.login')}}</button>
						<button class="block radius-btn" @click="register" type="primary" plain style="margin-top: 40rpx;">{{$t('General.login.register')}}</button>
				</view>
				<view v-if="!isPhone" class="read-agreement">
					<checkbox-group style="display: flex;align-items: center;" @change="bindchangeisRead">
						<checkbox :checked="isRead" color="#FF0025" style="transform:scale(0.7)" />
						<view class="">
                            {{$t('General.login.iAgree')}}{{' '}}<navigator url='/jvss/pagesMine/about-service/about-service'
								style="display: inline; color:#FF0025;">{{' '}}{{$t('General.login.common_service_agreement')}}{{' '}}</navigator>{{' '}}{{$t('General.login.and')}}{{' '}}<navigator
								url='/jvss/pagesMine/about-privacy-policy/about-privacy-policy'
								style="display: inline; color:#FF0025;">{{$t('General.login.common_privacy_policy_with_book_title')}}</navigator>
						</view>
					</checkbox-group>
				</view>
			</form>
		</view>
		<!-- 隐私协议 -->
		<uni-popup ref="popup">
			<view class="login-read-popup" style="width:70vw;height:auto;background: #FFFFFF;  ">
				<view class="login-read-popup-info" style="line-height: 1.75;">
                    {{$t('General.login.common_privacy_policy_one')}}
					<navigator url='/jvss/pagesMine/about-service/about-service'
						style="display: inline; color:#FF0025;"> {{$t('General.login.common_service_agreement')}}</navigator>
                    {{' '}}{{$t('General.login.and')}}{{' '}}
					<navigator url='/jvss/pagesMine/about-privacy-policy/about-privacy-policy'
						style="display: inline; color:#FF0025;">{{$t('General.login.common_privacy_policy_with_book_title')}}</navigator>
                    {{$t('General.login.common_privacy_policy_two')}}
				</view>
				<view class="u-f-r form-item-button">
					<view class="u-f-ajc cancel" @tap="cancel">{{$t('General.login.disagree')}}</view>
					<view class="u-f-ajc conf">
						<button @tap="iphoneConfrim" v-if="!isWeixinLogin"> {{$t('General.login.agree')}}</button>
						<button open-type="getUserInfo" @getphonenumber="getPhoneNumber" @chooseavatar="onChooseAvatar"
							@getuserinfo="bindgetuserinfo" @tap="getUserProfile" class="agree-button" v-else>{{$t('General.login.agree')}}</button>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	const CryptoJS = require('crypto-js');
	const {generateRandomString} = require('@/utils/util.js');
	const { BaseURL } = require('@/utils/api/baseUrl.js')
	export default {
		data() {
			return {
				type: null,
				uname: '',
				upass: '',
				isAutoLogin: true, // 自动登录的勾选
				isRemember: true, // 记住密码的勾选
				checkAutoLogin: '1', //判断是否自动登录
				isWeixinLogin: true, //是否微信登录
				isRead: false, //是否阅读
				isPhone: false, //是否手机号登录
				showPassword:true, // 是否显示密码
			};
		},
		onLoad: function(options) {
			this.isRemember = uni.getStorageSync('isRemember') == '1' ? true : false
			this.type = options.type ? options.type : null
			let checkAutoLogin = uni.getStorageSync('checkAutoLogin'); // 解密账户密码
			let unameDecrypt = CryptoJS.AES.decrypt(uni.getStorageSync('uname'), BaseURL);
			let upassDecrypt = CryptoJS.AES.decrypt(uni.getStorageSync('upass'), BaseURL);
			unameDecrypt = unameDecrypt.toString(CryptoJS.enc.Utf8);
			upassDecrypt = upassDecrypt.toString(CryptoJS.enc.Utf8); // 自动登录+记住密码
			if (this.isAutoLogin === true && this.isRemember === true) {
				this.uname = unameDecrypt
				this.upass = upassDecrypt
				if (checkAutoLogin === '1') {
					this.confrim();
				}
			}
			if (this.isAutoLogin === true && this.isRemember === false) {
				this.uname = unameDecrypt
			}
			// Token失效后，自动重新登录
			if(uni.getStorageSync('isTokenExpire')){
				if(uni.getStorageSync('isWeixinLogin')){
					this.$postPointData({code:'600104'})
					this.wxLogin()
				}else{
					this.confrim();
				}
			}
		},
		methods: {
			register(){
				uni.navigateTo({
					url:'./register'
				})
			},
			// 手机号登录返回
			backAction() {
				this.isPhone = false
			},
			// 隐私协议checkbox事件
			bindchangeisRead(ev) {
				if (ev.detail.value.length == 1) {
					this.isRead = true
				} else if (ev.detail.value.length == 0) {
					this.isRead = false
				}
			},
			// 账号输入事件
			bindinputUname(ev) {
				this.uname = ev.detail.value
			},
			// 密码输入事件
			bindinputUpass(ev) {
				this.upass = ev.detail.value
			},
			//自动登录
			bindchangeAutoLogin(ev) {
				if (ev.detail.value[0] === '1') {
					this.isAutoLogin = true
					this.isRemember = true
				} else {
					this.isAutoLogin = ''
					this.isRemember = true
				}
			},
			// 记住密码
			bindchangeRemember(ev) {
				if (ev.detail.value[0] === '1') {
					this.isAutoLogin = ''
					this.isRemember = true
					uni.setStorageSync('isRemember',this.isRemember)
					console.log('isRemember',this.isRemember)
				} else {
					this.isAutoLogin = ''
					this.isRemember = ''
					uni.setStorageSync('isRemember',this.isRemember)
					console.log('isRemember',this.isRemember)
				}
			},
			// 是否记住密码
			rememberPswd(e){
				this.isRemember = !this.isRemember;
				uni.setStorageSync('isRemember',this.isRemember)
				console.log('isRemember',this.isRemember)
			},
			// 手机号登录按钮
			iphoneLogin() {
				this.isWeixinLogin = false
				if (!this.isRead) {
					return this.$refs.popup.open()
				}
				this.isPhone = true;
			},
			// 手机号登录确认
			iphoneConfrim() {
				this.isRead = true;
				this.isPhone = true;
				return this.$refs.popup.close()
			},
			// 账号登录时使用
			formSubmit(ev) {
				let {
					uname,
					upass
				} = this;
				if (!uname) {
					uni.showToast({
						title: this.$t('General.login.accountPla'),
						icon: 'none'
					});
					return;
				}
				if (!upass) {
					uni.showToast({
						title: this.$t('General.login.pswPla'),
						icon: 'none'
					})
					return
				}
				this.confrim()
			},
			// 确认登录
			confrim() {
				this.$postPointData({code:'600103'})
				let {
					uname,
					upass
				} = this;
				uni.showLoading({
					title: this.$t('General.login.logging')
				});
				getApp().globalData.api.getUserInfo(uname, upass, (result) => {
					console.log('获取账户信息', result);
					this.$postPointData({code:'400114', eventName:'login_account_success'})
					uni.hideLoading({
						success: (res) => {
							uni.setStorageSync('isTokenExpire', false)
							uni.setStorageSync('isWeixinLogin', false)
							uni.setStorageSync('accessToken', result.accessToken);
							uni.setStorageSync('userInfo', {
								nickName: uname,
								avatarUrl: 'icon-gerenzhongxin2'
							}); // 加密账户密码
							this.getUserinfo2()
							let unameEncrypt = CryptoJS.AES.encrypt(uname, BaseURL)
								.toString();
							let upassEncrypt = CryptoJS.AES.encrypt(upass, BaseURL)
								.toString(); // 自动登录+记住密码
							if (this.isAutoLogin && this.isRemember) {
								uni.setStorageSync('uname', unameEncrypt);
								uni.setStorageSync('upass', upassEncrypt);
								uni.setStorageSync('isAutoLogin', '1');
								uni.setStorageSync('isRemember', '1');
								uni.setStorageSync('checkAutoLogin', '1');
							} // 记住密码
							else if (!this.isAutoLogin && this.isRemember) {
								uni.setStorageSync('uname', unameEncrypt);
								uni.setStorageSync('upass', upassEncrypt);
								uni.setStorageSync('isRemember', '1');
								uni.removeStorageSync('isAutoLogin');
								uni.removeStorageSync('checkAutoLogin');
							} // 无
							else if (!this.isAutoLogin && !this.isRemember) {
								uni.removeStorageSync('uname');
								uni.removeStorageSync('upass');
								uni.removeStorageSync('isAutoLogin');
								uni.removeStorageSync('isRemember');
								uni.removeStorageSync('checkAutoLogin');
							}
							console.log(this.type,'查看是不是分享')
							// if (this.type == 'share') {
							// 	uni.navigateBack()
							// } else {
							// 	this.toHome()
							// }
						}
					});
				});
			},

			/** 微信登录时使用 */
			onWeixinLogin() {
				this.isWeixinLogin = true
				if (!this.isRead) {
					return this.$refs.popup.open()
				}
				this.getUserProfile()
			},
			// 当open-type="getUserInfo"时，点击按钮触发执行bindgetuserinfo事件，以此执行此函数
			// 判断登录成功或是失败，以此继续执行wx.login接口
			bindgetuserinfo(ev) {
				console.log('微信登录：', ev);
				this.$postPointData({code:'600104'})
				if (ev.detail.errMsg !== 'getUserInfo:ok') {
					this.$postPointData({code:'400107'})
					uni.showToast({
						title: '登录失败'
					});
					return;
				}
				this.wxLogin();
			},
			// 调用 wx.login 接口获取临时登录凭证code，并回传到开发服务器
			wxLogin() {
				uni.showLoading({
					title: '登录中...'
				});
				uni.login({
					success: res => {
						if (res.errMsg === 'login:ok') {
							getApp().globalData.api.getAccessToken(res.code, (result) => {
								this.$postPointData({code:'400115', eventName:'login_third_success'})
								const accessToken = result.accessToken;
								uni.setStorageSync('isTokenExpire', false)
								uni.setStorageSync('isWeixinLogin', true);
								uni.setStorageSync('accessToken', accessToken);
								uni.hideLoading();
								this.getUserinfo2()
								// if (this.type == 'share') {
								// 	uni.navigateBack()
								// } else {
								// 	this.toHome()
								// }
								// uni.switchTab({
								//     url: '/jvss/pages/device/home'
								// });
							});
						}
					}
				})
			},
			// 跳转到登录
			toHome() {
				uni.setStorageSync('isToken', false);
				uni.setStorageSync('isOfficialAccounts',true);
				uni.switchTab({
					url: '/jvss/pages/device/home'
				});
			},
			/** 有关获取微信用户信息 */
			// 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
			getUserProfile(e) {
				this.isRead = true;
				this.$refs.popup.close()
				if (uni.getUserProfile) {
					// 授权
					uni.getUserProfile({
						desc: '展示用户信息',
						// 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
						success: (res) => {
							console.log('获取用户信息:', res);
							uni.setStorage({
								key: 'userInfo',
								data: res.userInfo,
								success: (res) => {
									// uni.switchTab({
									//     url: '/jvss/pages/device/home'
									// });
								}
							});
						},
						fail: (err) => {
							console.log('error:', err);
							uni.clearStorageSync();
						}
					});
				} else {
					uni.showModal({
						title: '提示',
						content: '请升级微信小程序'
					});
				}
			},
			// 忘记密码
			forgetAction() {
				uni.navigateTo({
					url: '/jvss/pagesMine/forget-password/forget-password?account='+this.uname
				})
			},
			// 获取用户信息
			getUserinfo2() {
				getApp().globalData.api.getUserinfo2((result) => {
					let userInfo = JSON.parse(decodeURIComponent(result.data.replace(/\+/g, '%20'))).data;
					if(typeof userInfo == 'object'){
						uni.setStorageSync('userInfo', userInfo);
					}
					console.log(userInfo, '用户信息',typeof userInfo)
					let clientId =  generateRandomString(24);
					uni.setStorageSync('openId',clientId);
				    getApp().globalData.mqtt.createConnect();
					if (this.type == 'share') {
						uni.navigateBack()
					} else {
						this.toHome()
					}
				})
			},
			// 关闭隐私协议弹窗
			cancel() {
				this.$refs.popup.close()
			},
			//获取手机号
			getPhoneNumber(e) {},
			//获取头像
			onChooseAvatar(e) {
				console.log('头像==', e);
			},
      changePassword() {
        this.showPassword = !this.showPassword;
      }
		}
	};
</script>
<style lang="scss">
	page {
		background-color: #ffffff;
	}
	.loginNav {
		/deep/ .uni-nav-bar-text {
			font-size: 34rpx !important;
			font-weight: bold;
		}
	}
	.login-read-popup {
		padding: 30rpx;
		border-radius: 20rpx;
	}
	.login-read-popup-info {
		font-size: 30rpx
	}
	.read-agreement {
		text-align: center;
		font-size: 24rpx;

	}
	.read-agreement text {
		color: #FF0025;
	}
	.logo {
		text-align: center;
		image{
			width: 150px;
		}
	}
	.logo-icon {
		height: 160rpx;
		width: 160rpx;
		margin: 120rpx 0;
		// justify-content: space-between;
	}
	.form {
		padding: 0 80rpx;
	}
	.form-item-button {
		margin-top: 20rpx;
		justify-content: space-around;
		.cancel {
			background: #F6F7FB;
			color: #000000;
			font-size: 30rpx;
			width: 237rpx;
			height: 84rpx;
			border-radius: 42rpx;
		}
		.conf {
			margin-left: 20rpx;
			background: #FF0025;
			color: #ffffff;
			font-size: 30rpx;
			width: 237rpx;
			height: 84rpx;
			border-radius: 42rpx;
			overflow: hidden;
			button {
				width: 100%;
				background: none;
				color: #ffffff;
			}
			button::after {
				border: none;
			}
		}
	}
	.forgetPwd {
		font-size: 24rpx;
	}
	.form-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		border-bottom: 1px solid #eeeeee;
		padding: 30rpx 0;
	}
	.space-between{
		justify-content: space-between;
	}
	.left{
		display: flex;
	}
	.form-item-title {
		//width: 100rpx;
        width: 165rpx;
	}
	.form-item-control {
		justify-content: space-between;
		color: #777777;
		margin-bottom: 80rpx;
		border-bottom: none;
	}
	.form-item-submit {
		flex-direction: column;
		border-bottom: none;
	}
	.agree-button {
		flex: 1;
		display: inline !important;
		width: auto !important;
		background: transparent !important;
		padding: 0 !important;
	}
	.agree-button::after {
		border: none;
	}
	.forgetPwd {
		color: #666;
		display: flex;
		justify-content: flex-end;
	}
</style>
